package com.fishingwithme.android.ui.screens.home

import android.Manifest
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Navigation
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Divider
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.core.content.ContextCompat
import androidx.hilt.navigation.compose.hiltViewModel
import com.fishingwithme.android.R
import com.fishingwithme.android.data.model.Line
import com.fishingwithme.android.ui.screens.map.TencentMapWrapper
import com.fishingwithme.android.ui.theme.AppDimensions
import com.fishingwithme.android.ui.viewmodels.NavigatorViewModel
import java.net.URLEncoder
import java.util.UUID

/**
 * 表示地图应用的简单数据类
 */
data class MapApp(
    val name: String,
    val packageName: String,
    val uriTemplate: (String, String, String) -> String
)

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun NavigatorScreen(
    spotId: String,
    moduleKey: String,
    viewModel: NavigatorViewModel = hiltViewModel()
) {
    // 当spotId变化时，通过ViewModel获取钓点信息
    LaunchedEffect(spotId) {
        viewModel.fetchSpotNavigationInfo(spotId)
    }

    // 获取ViewModel的UI状态
    val uiState by viewModel.uiState.collectAsState()

    Scaffold(
    ) { innerPadding ->
        val context = LocalContext.current
        var permissionsGranted by remember { mutableStateOf(false) }

        // 权限请求器
        val permissionLauncher = rememberLauncherForActivityResult(
            ActivityResultContracts.RequestMultiplePermissions()
        ) { permissions ->
            permissionsGranted = permissions.all { it.value }
        }

        // 检查权限
        DisposableEffect(Unit) {
            val requiredPermissions = arrayOf(
                Manifest.permission.INTERNET,
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION
            )

            val allGranted = requiredPermissions.all {
                ContextCompat.checkSelfPermission(context, it) == PackageManager.PERMISSION_GRANTED
            }

            if (!allGranted) {
                permissionLauncher.launch(requiredPermissions)
            } else {
                permissionsGranted = true
            }

            onDispose {}
        }

        // 只有当导航数据可用时才显示地图组件
        uiState.navLine?.let { navLine ->
            val data = remember(navLine) {
                mutableMapOf<String, Any>("line" to navLine)
            }

            // 地图组件
            TencentMapWrapper(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(innerPadding),
                permissionsGranted = permissionsGranted,
                moduleKey = moduleKey,
                data = data,
                changeKey = UUID.randomUUID().toString()
            )
        }

        // 添加地图导航按钮
        if (uiState.navLine != null && permissionsGranted) {
            // 状态：控制导航应用选择对话框的显示
            var showMapAppDialog by remember { mutableStateOf(false) }

            Box(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(innerPadding)
                    .padding(AppDimensions.SPACING_16),
                contentAlignment = Alignment.BottomCenter
            ) {
                Button(
                    onClick = {
                        showMapAppDialog = true
                    },
                    modifier = Modifier
                        .width(AppDimensions.BUTTON_HEIGHT_60)
                        .height(AppDimensions.BUTTON_HEIGHT_60)
                ) {
                    Icons.Filled.Navigation
                        .let {
                            Icon(
                                imageVector = it,
                                contentDescription = stringResource(R.string.navigate)
                            )
                        }
                }
            }

            // 导航应用选择对话框
            val line = uiState.navLine
            if (showMapAppDialog && line != null) {
                MapAppSelectionDialog(
                    context = context,
                    line = line,
                    onDismiss = { showMapAppDialog = false }
                )
            }
        }
    }
}

/**
 * 导航应用选择底部抽屉
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun MapAppSelectionDialog(
    context: Context,
    line: Line,
    onDismiss: () -> Unit
) {
    // 准备地图应用列表
    val gaodeMapName = stringResource(R.string.gaode_map)
    val baiduMapName = stringResource(R.string.baidu_map)
    val tencentMapName = stringResource(R.string.tencent_map)

    val mapApps = remember(context) {
        val allMapApps = listOf(
            MapApp(
                gaodeMapName,
                "com.autonavi.minimap",
                { lat, lon, name ->
                    "amapuri://route/plan/?sname=我的位置&dlat=$lat&dlon=$lon&dname=${
                        URLEncoder.encode(
                            name,
                            "UTF-8"
                        )
                    }&dev=0&t=0"
                }
            ),
            MapApp(
                baiduMapName,
                "com.baidu.BaiduMap",
                { lat, lon, name ->
                    "baidumap://map/direction?origin=我的位置&destination=name:${
                        URLEncoder.encode(
                            name,
                            "UTF-8"
                        )
                    }|latlng:$lat,$lon&mode=driving"
                }
            ),
            MapApp(
                tencentMapName,
                "com.tencent.map",
                { lat, lon, name ->
                    "qqmap://map/routeplan?from=我的位置&type=drive&tocoord=$lat,$lon&to=${
                        URLEncoder.encode(
                            name,
                            "UTF-8"
                        )
                    }&policy=0"
                }
            )
        )

        // 过滤出已安装的地图应用
        allMapApps.filter { isAppInstalled(context, it.packageName) }
    }

    // 如果没有已安装的特定地图应用，直接使用默认地图
    if (mapApps.isEmpty()) {
        LaunchedEffect(Unit) {
            openDefaultMapNavigation(context, line)
            onDismiss()
        }
        return
    }

    // 使用底部抽屉代替AlertDialog
    val sheetState = rememberModalBottomSheetState()
    ModalBottomSheet(
        onDismissRequest = onDismiss,
        sheetState = sheetState,
        content = {
            // 地图应用列表
            LazyColumn(
                modifier = Modifier
                    .padding(
                        horizontal = AppDimensions.SPACING_16,
                        vertical = AppDimensions.SPACING_8
                    )
            ) {
                items(mapApps) {
                    Button(
                        onClick = {
                            openSpecificMapNavigation(context, line, it)
                            onDismiss()
                        },
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(vertical = AppDimensions.SPACING_8)
                            .background(Color.LightGray.copy(alpha = 0.3f)),
                        colors = ButtonDefaults.buttonColors(
                            containerColor = Color.LightGray.copy(alpha = 0.4f)
                        )
                    ) {
                        Text(
                            it.name,
                            textAlign = TextAlign.Center,
                            color = Color.White
                        )
                    }
                    Divider(
                        modifier = Modifier.padding(horizontal = AppDimensions.SPACING_16),
                        color = Color.White.copy(alpha = 0.2f),
                        thickness = AppDimensions.BORDER_WIDTH_1
                    )
                }
            }

            // 取消按钮
            Button(
                onClick = onDismiss,
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(AppDimensions.SPACING_16)
                    .padding(bottom = AppDimensions.SPACING_32),
                colors = ButtonDefaults.buttonColors(
                    containerColor = Color.LightGray.copy(alpha = 0.4f)
                )
            ) {
                Text(
                    stringResource(R.string.cancel),
                    color = Color.White
                )
            }
        }
    )
}

/**
 * 打开指定的地图应用进行导航
 */
fun openSpecificMapNavigation(
    context: Context,
    line: Line,
    mapApp: MapApp
) {
    val destinationLatitude = line.latitude.toString()
    val destinationLongitude = line.longitude.toString()
    val destinationName = line.name

    val intent = Intent(Intent.ACTION_VIEW)
    intent.data =
        Uri.parse(mapApp.uriTemplate(destinationLatitude, destinationLongitude, destinationName))
    context.startActivity(intent)
}

/**
 * 打开默认地图应用进行导航
 */
fun openDefaultMapNavigation(
    context: Context,
    line: Line
) {
    val destinationLatitude = line.latitude.toString()
    val destinationLongitude = line.longitude.toString()
    val destinationName = line.name

    val intent = Intent(Intent.ACTION_VIEW)
    intent.data = Uri.parse(
        "http://maps.google.com/maps?daddr=$destinationLatitude,$destinationLongitude($destinationName)"
    )
    context.startActivity(intent)
}

/**
 * 检查指定包名的应用是否已安装
 * @param context 上下文
 * @param packageName 应用包名
 * @return 是否已安装
 */
fun isAppInstalled(context: Context, packageName: String): Boolean {
    return try {
        context.packageManager.getPackageInfo(packageName, 0)
        true
    } catch (e: PackageManager.NameNotFoundException) {
        false
    }
}



